<script setup lang="ts" name="Dict">
import { QForm, QTable, type FormItemRows, type TableColums } from '@meetjs/element-plus-kit'
import { checkPermission } from '@/utils/permission'
import { getDicts } from '@/api/system/dict/index'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { downloadBlobFile } from '@/utils'
import { listType, typeExport, delType, refreshCache } from '@/api/system/dictType/index'
import EditDialog from './components/EditDialog.vue'
import DictTag from '@/components/Dict/DictTag.vue'
import { warnBox } from '@/utils/utils'
import type { DictTypeItem, QueryParams } from '@/api/system/dictType/type'
import { debounce } from 'es-toolkit'
import { formatDate } from '@/utils/day'

const router = useRouter()

const formValue = ref<QueryParams & { daterange?: string[] }>({
	dictName: '',
	dictType: '',
	status: undefined,
	daterange: []
})

const sysNormalDisable = ref<IGetDictsRes>([])

const formOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '字典名称',
		prop: 'dictName',
		attrs: {
			placeholder: '请输入字典名称',
			clearable: true
		}
	},
	{
		type: 'input',
		label: '字典类型',
		prop: 'dictType',
		attrs: {
			placeholder: '请输入字典类型',
			clearable: true
		}
	},
	{
		type: 'select',
		label: '字典状态',
		prop: 'status',
		options: sysNormalDisable as unknown as any,
		attrs: {
			placeholder: '请选择字典状态',
			clearable: true,
			style: {
				width: '200px'
			}
		}
	},
	{
		type: 'date-picker',
		label: '创建时间',
		prop: 'daterange',
		attrs: {
			type: 'datetimerange',
			'range-separator': '至',
			'start-placeholder': '开始日期',
			'end-placeholder': '结束日期',
			'value-format': 'YYYY-MM-DD HH:mm:ss'
		}
	}
])

// 表格数据
const loading = ref(false)
const page = ref({
	currentPage: 1,
	pageSize: 10,
	total: 0
})
const tableData = ref<DictTypeItem[]>([])
const columns = ref<TableColums[]>([
	{
		type: 'index',
		label: '序号',
		align: 'center',
		width: 60
	},
	{
		label: '字典编号',
		prop: 'id'
	},
	{
		label: '字典名称',
		prop: 'dictName'
	},
	{
		label: '字典类型',
		prop: 'dictType'
	},
	{
		label: '状态',
		prop: 'status'
	},
	{
		label: '备注',
		prop: 'remark'
	},
	{
		label: '创建时间',
		prop: 'createTime'
	},
	{
		prop: 'action',
		fixed: 'right',
		label: '操作',
		width: 160,
		align: 'center'
	}
])

// 对话框
const editDialogRef = useTemplateRef('editDialogRef')

const getTableData = async () => {
	loading.value = true

	const params = {
		pageNum: page.value.currentPage,
		pageSize: page.value.pageSize,
		...formValue.value,
		'params[beginTime]': formValue.value.daterange?.[0],
		'params[endTime]': formValue.value.daterange?.[1]
	}
	delete params.daterange

	const res = await listType(params)
	tableData.value = res.data.rows
	page.value.total = res.data.total
	loading.value = false
}

const handleAdd = () => {
	editDialogRef.value?.init('add')
}

const handleEdit = (row: DictTypeItem) => {
	editDialogRef.value?.init('edit', String(row.id))
}

const handleDelete = async (rowId: string) => {
	await warnBox()
	await delType(rowId)
	ElMessage.success('删除成功')
	getTableData()
}

const handleExport = debounce(() => exportFn(), 800, {
	edges: ['leading']
})
const exportFn = () => {
	const params = {
		pageNum: page.value.currentPage,
		pageSize: page.value.pageSize,
		...formValue.value,
		'params[beginTime]': formValue.value.daterange?.[0],
		'params[endTime]': formValue.value.daterange?.[1]
	}
	delete params.daterange

	typeExport(params).then(data => {
		downloadBlobFile(data.data, data.filename ? data.filename : `dict_${new Date().getTime()}.xlsx`)
	})
}

const handleRefreshCache = async () => {
	await refreshCache()
	ElMessage.success('刷新成功')
}

const handleDictData = (row: DictTypeItem) => {
	router.push(`/system/dict-data/index/${row.id}`)
}

const init = () => {
	getDicts('sys_sys_normal_disable').then(data => {
		sysNormalDisable.value = data
	})
}

onMounted(() => {
	init()
	getTableData()
})
</script>

<template>
	<div class="table-page-box">
		<div class="filter-box">
			<QForm
				inline
				:model="formValue"
				:form-options="formOptions"
				:buttons="['search', 'reset']"
				@search="getTableData"
				@reset="getTableData"
			/>
		</div>
		<div class="table-box">
			<QTable
				:data="tableData"
				:columns="columns"
				:page="page"
				:loading="loading"
				style="width: 100%"
				@pageChange="getTableData"
			>
				<template #headerLeft>
					<el-button
						v-if="checkPermission(['system:dict:add'])"
						type="primary"
						@click="handleAdd"
					>
						新增
					</el-button>
					<el-button
						v-if="checkPermission(['system:dict:export'])"
						@click="handleExport"
					>
						导出
					</el-button>
					<el-button
						v-if="checkPermission(['system:dict:remove'])"
						@click="handleRefreshCache"
					>
						刷新缓存
					</el-button>
				</template>
				<template #dictType="{ row }">
					<el-link
						type="primary"
						@click="handleDictData(row)"
					>
						{{ row.dictType }}
					</el-link>
				</template>
				<template #status="{ row }">
					<DictTag
						:options="sysNormalDisable"
						:value="row.status"
					/>
				</template>
				<template #createTime="{ row }">
					{{ formatDate(row.createTime) }}
				</template>
				<template #action="{ row }">
					<el-button
						v-if="checkPermission(['system:dict:edit'])"
						type="primary"
						link
						@click="handleEdit(row)"
					>
						修改
					</el-button>
					<el-button
						v-if="checkPermission(['system:dict:remove'])"
						type="danger"
						link
						@click="handleDelete(row.id)"
					>
						删除
					</el-button>
				</template>
			</QTable>
		</div>
		<EditDialog
			ref="editDialogRef"
			@refresh="getTableData"
		/>
	</div>
</template>
